package net.suncaper.demo.controller;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import net.suncaper.demo.domain.Message;
import net.suncaper.demo.domain.Order;
import net.suncaper.demo.domain.User;
import net.suncaper.demo.service.OrderService;
import net.suncaper.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private OrderService orderService;

    @GetMapping
    public String IndexPages(HttpServletRequest request,Model model){
        HttpSession session=request.getSession();
        Long userid = (Long)session.getAttribute("userID");
        User user = userService.selectByPrimaryKey(userid);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        if(user.getBirthday()!=null)
        { String birthday = format.format(user.getBirthday());
            model.addAttribute("birthday",birthday);
        }
        //System.out.println(birthday);

        List<Order> ordersBook = orderService.selectByStatus("未支付",userid);
        List<Order> ordersConfirm = orderService.selectByStatus("已支付",userid);
        model.addAttribute("user",user);
        model.addAttribute("ordersBook",ordersBook);
        model.addAttribute("ordersConfirm",ordersConfirm);


        return "pages/user/user.html";
    }

    @GetMapping("/login")
    public String LoginPage(HttpServletRequest request){
        return "pages/user/login.html";
    }

    @PostMapping("/login")
    public String Login(User user, HttpServletRequest request , HttpServletResponse response){
        //根据用户ID从数据库获得该ID的密码，然后判断
       // System.out.println(user.getTelephone()+"!@#!@#!@#!@#!@#!@#@!#@!");
        int res = userService.checkUser(user);
        if( res == 2)//成功
        {
            //session
            List<User> users=userService.selectByTele(user);
            HttpSession session=request.getSession();
            session.setAttribute("userID",users.get(0).getUserid());
            session.setAttribute("userTel",users.get(0).getTelephone());
            return "redirect:/hotel/search";
        }
        else if(res == 1)//用户不存在
        {
            return "/pages/user/loginfailed.html";
        }else{//登录失败
            return "/pages/user/loginfailed.html";
        }
    }

    @GetMapping("/register")
    public String loginPages(HttpServletRequest request) {
        return "pages/user/registration.html";
    }

//    @PostMapping("/register")
//    public String Register(HttpServletRequest request,User user, @RequestParam("password2") String password2)
//    {
//        int check = userService.checkUser(user);
//        if(check==1){ //用户名不存在
//            if(user.getPassword().equals(password2)){
//                user.setUserid(null);
//                userService.saveUser(user);
//                return "pages/user/registersuccess.html";
//            }else{
//                return "pages/user/registerfailed2.html";
//            }
//        }
//        else{
//            return "pages/user/registerfailed.html";
//        }
//    }

    @GetMapping("/modify")
    public String userModifyPages(HttpServletRequest request,Model model){
        HttpSession session=request.getSession();
        Long userid = (Long)session.getAttribute("userID");
        User user = userService.selectByPrimaryKey(userid);

        model.addAttribute("user",user);
        return"/pages/user/userModify.html";
    }

    @PostMapping("/modify")
    public String userModifyPages2(HttpServletRequest request,Model model,@RequestParam("userName")String name,
                                   @RequestParam("sex")String sex,@RequestParam("birthday")String birthday){
        HttpSession session=request.getSession();
        Long userID = (Long)session.getAttribute("userID");
        userService.updateByID(userID,name,sex,birthday);
        Long userid = (Long)session.getAttribute("userID");
        User user = userService.selectByPrimaryKey(userid);
        if(user.getBirthday()!=null){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String birthdays = format.format(user.getBirthday());
            model.addAttribute("birthday",birthdays);
        }

        //System.out.println(birthday);

        List<Order> ordersBook = orderService.selectByStatus("未支付",userid);
        List<Order> ordersConfirm = orderService.selectByStatus("已支付",userid);
        model.addAttribute("user",user);
        model.addAttribute("ordersBook",ordersBook);
        model.addAttribute("ordersConfirm",ordersConfirm);


        return "pages/user/user.html";
    }

    @GetMapping("/exit")
    public String exit(HttpServletRequest request){
        HttpSession session=request.getSession();
        session.removeAttribute("userID");
        return "redirect:/hotel/search";
    }

    @PostMapping("/register")
    public String sendMsg(HttpServletRequest request, HttpServletResponse response,User user, @RequestParam("password2") String password2) throws ClientException {
        int check = userService.checkUser(user);
        System.out.println("check= "+check );
        System.out.println("tel= "+user.getTelephone());
        System.out.println("password= "+user.getPassword() );
        String userTel=user.getTelephone();
        if(check!=1) {//用户名已经存在
//            System.out.println("check= "+check );
            return "pages/user/registerfailed.html";
        }
        else if(!user.getPassword().equals(password2)){
                return "pages/user/registerfailed2.html";
//                user.setUserid(null);
//                userService.saveUser(user);

            }
        else{
            long phonenumber = Long.parseLong(userTel);//获取前端传送过来的电话号码
            String phoneNumber= String.valueOf(phonenumber);
            String randomNum = createRandomNum(4);//随机生成6位数的验证码
            System.out.println(randomNum);
            String jsonContent = "{\"code\":\"" + randomNum + "\"}";//这里的code对应在阿里大于创建短信模板时的${code}
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("phoneNumber", userTel);
            paramMap.put("jsonContent", "{\"code\":\"" + randomNum + "\"}");
            SendSmsResponse sendSmsResponse = Message.sendSms(paramMap); //阿里大于发送机制
            if(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
                System.out.println(paramMap);
                System.out.println("短信验正码发送成功！");
                request.getSession().setAttribute("randomNum",randomNum );
                request.getSession().setAttribute("userTel",user.getTelephone());
                request.getSession().setAttribute("password",user.getPassword());
                request.getSession().setAttribute("user",user);
                return "redirect:/user/check";
            }
            else {
                System.out.println(sendSmsResponse.getCode()+" 短信发送失败！");
                return "pages/user/registration.html";
            }
            }
    }
    @GetMapping("/check")
    public String check(){
        return "/pages/user/telcheck.html";
    }

    @PostMapping("/check")
    public String checkRadomnum(HttpServletRequest request,HttpServletResponse response,User user,@RequestParam("checknum") String num,@RequestParam("realnum")String checknum) {
        HttpSession session=request.getSession();
        if (checknum.equals(num)){
            System.out.println("短信验正码正确！");
            userService.saveUser(user);
            return "/pages/user/regisucess.html";
        }
        else {
            System.out.println("短信验正码错误！");
            return "/pages/user/regifail.html";
        }

    }


    public static String createRandomNum(int num){
        String randomNumStr = "";
        for(int i = 0; i < num;i ++){
            int randomNum = (int)(Math.random() * 10);
            randomNumStr += randomNum;
        }
        return randomNumStr;
    }


}